import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ListPage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return ListState();
  }
}

class ListState extends State<ListPage> {
  String _result = '';

  @override
  void initState() {
    super.initState();
    receiveMessage();
  }

  //创建 BasicMessageChannel
  // flutter_and_native_100 为通信标识
  // StandardMessageCodec() 为参数传递的 编码方式
  static const messageChannel = const BasicMessageChannel(
      'ace_demo_android_flutter', StandardMessageCodec());

  //发送消息
  Future<Map> sendMessage(Map arguments) async {
    Map reply = await messageChannel.send(arguments);
    //解析 原生发给 Flutter 的参数
    int code = reply["code"];
    String message = reply["message"];

    //更新 Flutter 中页面显示
    setState(() {
      _result = "code:$code message:$message";
    });
    return reply;
  }

  //接收消息监听
  void receiveMessage() {
    messageChannel.setMessageHandler((result) async {
      //解析 原生发给 Flutter 的参数
//      int code = result["code"];
//      String message = result["message"];
      String s = result;
      setState(() {
        _result = "receiveMessage: code:$result";
      });
      return 'Flutter 已收到消息';
    });
  }

  _sendToAndroid(){
    sendMessage({"method": "test", "ontent": "flutter 中的数据", "code": 100});
  }

  @override
  void dispose() {
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: new Center(
          child: new GestureDetector(
            child: new Text(
              _result,
              style: TextStyle(color: Colors.black, fontSize: 18.0),
            ),
            onTap: () {
              _sendToAndroid();
            },
          ),
        ));
  }
}